package org.jfsm.log;

public class LogSource {

	protected boolean enabled;
    private static final long start = System.nanoTime();
    
	private Logger logger;
    private static Logger defaultLogger = new NullLogger();
    
    private String name = "FSM";
    
    public LogSource() {
		this(null);
	}
    
    public LogSource(Logger logger) {
        if(logger==null) {
            if(defaultLogger!=null) logger = defaultLogger;
        }

        logger.register(this);
        
        this.logger = logger;
    }

	public static void setDefaultLogger(Logger logger) {
        defaultLogger = logger;
    }
    
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    
    public boolean isEnabled() {
    	return enabled;
    }

    public final void log(String str) {
    	logger.log(str);
    }

    public final void log(String str, Object... str2) {
    	if( !enabled ) return;
    		
        StringBuilder sb = new StringBuilder();
        String time = String.valueOf( System.nanoTime() - start ); 
        sb.append("                   ".substring(0,20-time.length()));
        sb.append(time);
        sb.append("      ");
        sb.append(str);
        for(Object s:str2) {
        	sb.append(s);
        }
        sb.append("\n");
        logger.log( sb.toString() );
    }
    
    protected StringBuilder newSB() {
        StringBuilder sb = new StringBuilder();
        String time = String.valueOf( System.nanoTime() - start ); 
        sb.append("                   ".substring(0,20-time.length()));
        sb.append(time);
        sb.append(", ");
        sb.append(name);
        sb.append(" ");
        return sb;
    }
    
    public void setName(String name) {
    	this.name= name;
    }
}
